// page/component/new-pages/cart/cart.js
import requst from '../../../util/Http.js'

Page({
  data: {
    address:{},
    hasAddress:false,
    carts:[],               // 购物车列表
    hasList:false,          // 列表是否有数据
    totalPrice:0,           // 总价，初始为0
    selectAllStatus:true    // 全选状态，默认全选
  },
  onLoad(ops){
    let token=wx.getStorageSync('token')
    if(token.length==0){
      wx.navigateTo({
        url: '/page/component/login/login',
      })
      return
    }
  },
  onShow() {
    let self=this;
    wx.getStorage({
      key: 'address',
      success: function(res){
        console.log(res)
          self.setData({
            hasAddress:true,
            address:res.data
          })
      },
      fail(err){
        console.log(err)
      }
    })

    let list=wx.getStorageSync('cartList');
    if(list!==undefined||list!==null){
      this.setData({
        hasList:true,
        carts:list,
      });
      this.getTotalPrice();
    }
  },
  /**
   * 当前商品选中事件
   */
  selectList(e) {
    const index = e.currentTarget.dataset.index;
    let carts = this.data.carts;
    const selected = carts[index].selected;
    carts[index].selected = !selected;
    let arr=carts.filter(item=>{
     return item.selected==false
    })
    this.setData({
      carts: carts,
      selectAllStatus:arr.length?false:true,
    });
    this.getTotalPrice();
  },

  /**
   * 删除购物车当前商品
   */
  deleteList(e) {
    const index = e.currentTarget.dataset.index;
    let carts = this.data.carts;
    let list=wx.getStorageSync('cartList')
    list.splice(index,1);
    wx.setStorageSync('cartList',list);
    this.setData({
      carts: list
    });
    if(!carts.length){
      this.setData({
        hasList: false
      });
    }else{
      this.getTotalPrice();
    }
  },

  /**
   * 购物车全选事件
   */
  selectAll(e) {
    let carts = this.data.carts;

    for (let i = 0; i < carts.length; i++) {
      carts[i].selected = selectAllStatus;
    }
    this.setData({
      selectAllStatus: selectAllStatus,
      carts: carts
    });
    this.getTotalPrice();
  },


  setOrders(){
      let list=this.data.carts;
      let address=this.data.address;
      try{
        let arr=list.filter(item=>{
          return item.selected==true
        });

        if(Object.keys(address).length==0){
          wx.showToast({
            icon:'error',
            title: '请选择地址',
          })
          return
        }
        if(arr.length>0){
            this.useroerder(arr)
        }else{
          wx.showToast({
            icon:'error',
            title: '请选择商品',
          })
        }
      }catch{
        wx.showToast({
          icon:'error',
          title: '当前没有商品',
        })
      }
  },

  // 下订单
  useroerder(list){
    wx.showLoading({
      title: '结算中',
    })
    let arr=[];
    let total_count=0;
    let total_price=0;
    for(let i=0;i<list.length;i++){
      let obj={id:list[i].id,name:list[i].name,main_img_url:list[i].main_img_url,price:list[i].price,totalNum:list[i].totalNum}
      total_count+=list[i].totalNum;
      total_price+=Number(list[i].price)*list[i].totalNum;
      arr.push(obj)
    }
    let than=this;
    let newobj={
      total_count,
      total_price,
      user_id:wx.getStorageSync('userinfo').id,
      snap_address:than.data.address,
      status:1,
      list:arr,
    }

    requst('/Index/addOrder',newobj,'post').then(res=>{
      if(res.code==200){
        let newlist=than.data.carts;
        let newarr=newlist.filter(item=>{
          return item.selected==false
        });
        wx.setStorageSync('cartList',newarr)
        wx.hideLoading()
        wx.navigateTo({
          url: '/page/component/orders/orders?id='+res.data,
        })
      }
    })
  },

  /**
   * 绑定加数量事件
   */
  addCount(e) {
    const index = e.currentTarget.dataset.index;
    let carts = this.data.carts;
    let num = carts[index].totalNum;
    num = num + 1;
    carts[index].totalNum = num;
    this.setData({
      carts: carts
    });
    this.getTotalPrice();
    wx.setStorageSync('cartList',carts);
  },

  /**
   * 绑定减数量事件
   */
  minusCount(e) {
    const index = e.currentTarget.dataset.index;
    let carts = this.data.carts;
    let num = carts[index].totalNum;
    if(num <= 1){
      return false;
    }
    num = num - 1;
    carts[index].totalNum = num;
    this.setData({
      carts: carts
    });
    this.getTotalPrice();
    wx.setStorageSync('cartList',carts);
  },

  /**
   * 计算总价
   */
  getTotalPrice() {
    let carts = this.data.carts;                  // 获取购物车列表
    let total = 0;
    for(let i = 0; i<carts.length; i++) {         // 循环列表得到每个数据
      if(carts[i].selected) {                     // 判断选中才会计算价格
        total += carts[i].totalNum * carts[i].price;   // 所有价格加起来
      }
    }
    this.setData({                                // 最后赋值到data中渲染到页面
      carts: carts,
      totalPrice: total.toFixed(2)
    });
  }

})